package com.shoppingmalltest.shoppingmalltest.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shoppingmalltest.common.utils.PageUtils;
import com.shoppingmalltest.common.utils.Query;

import com.shoppingmalltest.shoppingmalltest.product.dao.SubjectDao;
import com.shoppingmalltest.shoppingmalltest.product.entity.SubjectEntity;
import com.shoppingmalltest.shoppingmalltest.product.service.SubjectService;


@Service("subjectService")
public class SubjectServiceImpl extends ServiceImpl<SubjectDao, SubjectEntity> implements SubjectService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SubjectEntity> page = this.page(
                new Query<SubjectEntity>().getPage(params),
                new QueryWrapper<SubjectEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SubjectEntity> getChildren() {
        //查询出所有商品
        List<SubjectEntity> subjectEntities = baseMapper.selectList(null);

        //组装父子结构
        List<SubjectEntity> collect = subjectEntities.stream().filter(subjectEntitie ->
                subjectEntitie.getParentId().equals("0")
        //通过Map映射处理数据返回
        ).map((map)->{
            //通过递归方式
            map.setChildren(getChildrens(map,subjectEntities));
            return map;
        //根据数据库sort字段排序
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
            //返回集合
        }).collect(Collectors.toList());

         return collect;
    }

    @Override
    public void removeMenusByIds(List<String> strings) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(strings);
    }

    private List<SubjectEntity> getChildrens(SubjectEntity root, List<SubjectEntity> all) {

        List<SubjectEntity> collect = all.stream().filter((allList) -> {
            return allList.getParentId().equals(root.getId());
        }).map((map)->{
            map.setChildren(getChildrens(map,all));
            return map;
        }).sorted((meun1,menu2)->{
            return (meun1.getSort()==null?0:meun1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return collect;
    }

}